<template>
  <div>
    <div class="text-xl font-bold mb-4">工单审批</div>
    <a-row :gutter="[32, 8]" :style="{ minHeight: '900px' }">
      <a-col :span="24">
        异常工单
        <vxe-grid ref="xGrid" v-bind="gridOptions" v-on="gridEvent">
        <template #car="{ row }">
            {{ row.repair.car?`${row.repair.car.serial}`:'' }}
          </template>
          <template #repair="{ row }">
            {{ row.repair.order_no }}
          </template>
          <template #ticket_type="{ row }">
          <div>
            <a-tag color="success" v-if="row.ticket_type == 1">正常工单</a-tag>
            <a-tag color="error" v-else>异常工单</a-tag>
          </div>

          </template>
          <template #state="{ row }">
          <div>
            <a-tag color="success" v-if="row.state >= 5">完结</a-tag>
            <a-tag color="error" v-else>在途</a-tag>
          </div>

          </template>
          <template #kind="{ row }">
            {{ row.kind.union_name }}
          </template>
          <template #services="{ row }">
            {{ row.services.map((i) => i.name).toString(",") }}
          </template>
          <template #add_services="{ row }">
            {{
              row.add_services_ids
                ? row.add_services_ids.map((i) => i).toString(",")
                : ""
            }}
          </template>

          <template #users="{ row }">
            {{ row.users.map((item) => item.name).toString(",") }}
          </template>
          <template #process="{ row }">
            <a-button type="link" @click="showProcess(row)"> 查看流程</a-button>
          </template>
          <template #action="{ row }">
            <a-button
              type="primary"
              @click="signAction(row)"
              v-if="row.state == 1"
            >
              签字</a-button
            >
            <a-popconfirm
              title="确认完结该工单?"
              ok-text="Yes"
              cancel-text="No"
              @confirm="overAction(row)"
            >
              <a-button type="primary" v-if="row.state == 2">
                班长确认</a-button
              >
            </a-popconfirm>
           <a-popconfirm
              title="确认完结该工单?"
              ok-text="Yes"
              cancel-text="No"
              @confirm="confirmAction(row)"
            >
              <a-button type="primary" v-if="row.state == 3 &&hasPers('flow_role')">
                作业长确认</a-button
              >
            </a-popconfirm>
            
          </template>
        </vxe-grid>
        <!--              签字-->
        <a-modal
          v-model:open="open"
          centered
          title="操作"
          :footer="false"
          width="1000px"
          :bodyStyle="{
            height: '700px',
          }"
        >
          <a-form
            :model="approveForm"
            :label-col="{ span: 2 }"
            :wrapper-col="{ span: 24 }"
          >
            <a-form-item-rest>
              <a-steps :current="current" :items="items"></a-steps>
            </a-form-item-rest>
            <div class="steps-content">
              <a-form-item label="客户签名" v-show="current == 0">
                <div class="flex">
                  <div>
                    <vue-esign
                      ref="esign1"
                      :width="500"
                      :height="400"
                      bgColor="#ebfbee"
                      :isClearBgColor="false"
                      style="border: 2px dotted #ddd"
                    />
                    <a-space class="mt-2">
                      <a-button type="primary" @click="confirmEsign1"
                        >确认</a-button
                      >
                      <a-button type="primary" danger @click="resetEsign1"
                        >清空</a-button
                      >
                    </a-space>
                  </div>
                  <DoubleRightOutlined class="text-xl font-bold mx-2" />
                  <div>
                    <a-image
                      :src="approveForm.customer_sign"
                      :width="250"
                    ></a-image>
                  </div>
                </div>
              </a-form-item>
              <a-form-item label="维修工签名" v-show="current == 1">
                <div class="flex">
                  <div>
                    <vue-esign
                      ref="esign2"
                       :width="500"
                      :height="400"
                      bgColor="#ebfbee"
                      :isClearBgColor="false"
                      style="border: 2px dotted #ddd"
                    />
                    <a-space class="mt-2">
                      <a-button type="primary" @click="confirmEsign2"
                        >确认</a-button
                      >
                      <a-button type="primary" @click="resetEsign2" danger
                        >清空</a-button
                      >
                    </a-space>
                  </div>
                  <DoubleRightOutlined class="text-xl font-bold mx-2" />
                  <div>
                    <a-image
                      :src="approveForm.user_sign"
                      :width="250"
                    ></a-image>
                  </div>
                </div>
              </a-form-item>
            </div>
            <div class="steps-action text-center">
              <a-button
                v-if="current < steps.length - 1"
                type="primary"
                size="large"
                @click="next"
                >下一步</a-button
              >
              <a-button
                size="large"

                v-if="current == steps.length - 1"
                type="primary"
                @click="onSubmit"
              >
                完成提交
              </a-button>
              <a-button
                size="large"

                v-if="current > 0"
                style="margin-left: 8px"
                @click="prev"
                >上一步</a-button
              >
            </div>
          </a-form>
        </a-modal>

        <!--              流程-->
        <a-modal
          v-model:open="process_open"
          centered
          width="1000px"
          title="查看流程"
          :footer="false"
        >
          <a-steps :items="process_steps"></a-steps>
          <div class="mt-3">
            <vxe-table
              border
              show-overflow
              keep-source
              :resize-config="{}"
              :is-hover="true"
              ref="xTable"
              :column-config="{ resizable: true }"
              :data="current_ticket.processes"
            >
              <vxe-column
                field="id"
                title="流程id"
                sortable
                width="100"
              ></vxe-column>
              <vxe-column
                field="ticket_id"
                title="维修单id"
                sortable
                width=""
              ></vxe-column>
              <vxe-column
                field="state"
                title="当前状态"
                sortable
                width=""
              ></vxe-column>
              <vxe-column
                field="pid"
                title="前一流程ID"
                sortable
                width=""
              ></vxe-column>
              <vxe-column
                field="created_at"
                title="时间"
                sortable
                width=""
              ></vxe-column>
              <vxe-column field="operation" title="操作" sortable width="">
              </vxe-column>
            </vxe-table>
            <div class="text-center mt-3">
              <a-button
                type="primary"
                size="large"
                style="width: 300px"
                @click="process_open = false"
                >确定</a-button
              >
            </div>
          </div>
        </a-modal>
        <!--              异常工单-->
        <a-modal
          v-model:open="abnormal_open"
          centered
          width="1000px"
          title="异常工单"
          :footer="false"
        >
          
            <a-descriptions title="当前工单" bordered size="small">
              <a-descriptions-item label="报修单id">{{
                ticketForm.id
              }}</a-descriptions-item>
              <a-descriptions-item label="维修方式">{{
                ticketForm.repair_way
              }}</a-descriptions-item>
              <a-descriptions-item label="车位">{{
                ticketForm.parking_id
              }}</a-descriptions-item>
              <a-descriptions-item label="车型">{{
                ticketForm.kind.union_name
              }}</a-descriptions-item>
              <a-descriptions-item label="工单类型">{{
                ticketForm.ticket_type
              }}</a-descriptions-item>
              <a-descriptions-item label="维修工">
              <div v-for="(s, index) in ticketForm.users" :key="index">
                  <span :class="ticketForm.add_users_ids.includes(s.id)?'active':''">{{ s.name }}</span>
                  <a-tag
                    color="cyan"
                    v-if="ticketForm.add_users_ids.includes(s.id)"
                    >添加维修工</a-tag
                  >
                  <br />
                </div>
              </a-descriptions-item>
              
              <a-descriptions-item label="服务项目">
                <div v-for="(s, index) in ticketForm.services" :key="index">
                  <span :class="ticketForm.add_services_ids.includes(s.id)?'active':''">{{ s.name }}</span>
                  <a-tag
                    color="cyan"
                    v-if="ticketForm.add_services_ids.includes(s.id)"
                    >添加项目</a-tag
                  >
                  <br />
                </div>
              </a-descriptions-item>
            </a-descriptions>
            <div class="mt-3">
            <a-card>
              <a-form
                ref="formRef"
                :model="confirmForm"
                :label-col="{ span: 6 }"
                :wrapper-col="{ span: 24 }"
                class="border border-gray-200 solid"
              >
              <a-form-item
                  label="审批意见"
                  name="comment"
                  :rules="[
                    ruleStore.getRule('comment')
                      ? ruleStore.getRule('comment')
                      : { required: false },
                  ]"
                >
                 <a-textarea v-model:value="confirmForm.comment">
                 </a-textarea>
                </a-form-item>
                <a-form-item
                  label="是否同意"
                  name="agree"
                  :rules="[
                    ruleStore.getRule('agree')
                      ? ruleStore.getRule('agree')
                      : { required: false },
                  ]"
                >
                  <a-radio-group
                    v-model:value="confirmForm.agree"
                    name="radioGroup"
                  >
                    <a-radio :value="true">同意</a-radio>
                    <a-radio :value="false">不同意</a-radio>
                  </a-radio-group>
                </a-form-item>
                <a-form-item :wrapper-col="{ offset: 8, span: 24 }">
                  <a-button type="primary" @click="submitAbnormal" style="width: 300px">提交</a-button>
                </a-form-item>
              </a-form>
          </a-card>

            </div>
        </a-modal>
      </a-col>
    </a-row>
  </div>
</template>

<script setup lang="ts">
import Api from "@/api/backend/api";
import { message } from "ant-design-vue";
import useApproval from "./useAbApproval";
import useRuleStore from "@/store/modules/rule";

import {
  UserOutlined,
  SolutionOutlined,
  LoadingOutlined,
  SmileOutlined,
} from "@ant-design/icons-vue";

import { DoubleRightOutlined } from "@ant-design/icons-vue";

const hasPers = inject('hasPers');

const ruleStore = useRuleStore();
const { gridOptions, ticket_type } = useApproval();
ticket_type.value = 2;
const xGrid = ref();
const gridEvent: VxeGridListeners<RowVO> = {
  proxyQuery() {
    console.log("数据代理查询事件");
    const grid = xGrid.value;
    // 获取表格中的数据
    // const data = grid.getTableData().fullData;
    // console.log(data);
  },
  proxyDelete() {
    console.log("数据代理删除事件");
  },
  proxySave() {
    console.log("数据代理保存事件");
  },
};
const baseUrl = `${import.meta.env.VITE_BASE_API_URL}/upload/`;
const open = ref(false);
const process_open = ref(false);
const abnormal_open = ref(false);
const tickets = ref([]);
const esign1 = ref();
const esign2 = ref();
const approveForm = ref({
  id: null,
  customer_sign: "",
  user_sign: "",
});

const getTicket = async () => {
  tickets.value = await Api.ticketController.toDo();
};
const signAction = (row) => {
  approveForm.value.id = row.id;
  open.value = true;
};
const current_ticket = ref({});
const showProcess = async (row) => {
  current_ticket.value = row;
  let process_items = [];
  const stateItems = await Api.processStateController.list({
    type: row.ticket_type,
  });
  process_items = stateItems.map((item) => {
    let status = "wait";
    if (row.state > item.status) {
      status = "finish";
    }
    if (row.state == item.status) {
      status = "process";
    }
    if (row.state < item.status) {
      status = "wait";
    }
    return {
      title: item.status_name,
      subTitle: item.comment,
      description: item.role_name,
      status: status,
    };
  });

  process_steps.value = process_items;
  process_open.value = true;
};
const confirmEsign1 = () => {
  esign1.value
    .generate({ format: "image/jpeg", quality: 1 })
    .then(async (res) => {
      const url = await uploadBase64Image(res);
      approveForm.value.customer_sign = `${baseUrl}${url}`;
    })
    .catch((err) => {
      alert(err); // 画布没有签字时会执行这里 'Not Signned'
    });
};
//签字相关
const current = ref(0);
const next = () => {
  if (
    approveForm.value.id == null ||
    approveForm.value.customer_sign == ""
  ) {
    return message.error("请完成签字");
  }
  current.value++;
};
const prev = () => {
  current.value--;
};
const steps = [
  {
    title: "维修工签字",
    content: "First-content",
  },
  {
    title: "客户签字",
    content: "Second-content",
  },
];
const items = steps.map((item) => ({ key: item.title, title: item.title }));
const resetEsign1 = () => {
  esign1.value.reset();
};
const resetEsign2 = () => {
  esign2.value.reset();
};
const confirmEsign2 = () => {
  esign2.value
    .generate({ format: "image/jpeg", quality: 1 })
    .then(async (res) => {
      const url = await uploadBase64Image(res);
      approveForm.value.user_sign = `${baseUrl}${url}`;
    })
    .catch((err) => {
      alert(err); // 画布没有签字时会执行这里 'Not Signned'
    });
};

const uploadBase64Image = async (base64String) => {
  // 1. 将Base64数据转换为Blob对象
  const byteCharacters = atob(base64String.split(",")[1]);
  const byteArrays = [];
  for (let i = 0; i < byteCharacters.length; i++) {
    byteArrays.push(byteCharacters.charCodeAt(i));
  }
  const blob = new Blob([new Uint8Array(byteArrays)], { type: "image/jpeg" });
  // 根据Blob对象生成File对象
  const file = new File([blob], "file.jpeg", { type: "image/jpeg" });

  const data = await Api.uploadController.upload({}, file);
  return data;
};

const init = () => {
  getTicket();
};
init();

const onSubmit = async () => {
  if (
    approveForm.value.id == null ||
    approveForm.value.user_sign == "" ||
    approveForm.value.customer_sign == ""
  ) {
    return message.error("请完成签字");
  }
  await Api.ticketController.sign(approveForm.value);
  setTimeout(()=>{
    open.value=false
    xGrid.value.commitProxy("query");
    },500)
};

//流程相关
const process_steps = ref([]);


//申请异常
const applyProcess = async (row) => {
  console.log(row);
  xGrid.value.commitProxy("query");
};

const overAction = async (row) => {
  await Api.ticketController.pass({
    id: row.id,
  });
  xGrid.value.commitProxy("query");
};

//异常工单详情
const ticketForm = ref({});
const confirmForm = ref({
  agree: false,
  id: null,
  comment:''
});
const confirmAction = async (row) => {
  ticketForm.value = await Api.ticketController.abNormalDetail({
    id: row.id,
  });
  confirmForm.value.id=row.id
  abnormal_open.value = true;
};

const submitAbnormal = async (row) => {
  await Api.ticketController.confirm(confirmForm.value);
  xGrid.value.commitProxy("query");
  abnormal_open.value = false;
};
</script>

<style lang="less">
.full-modal {
  .ant-modal {
    max-width: 100%;
    top: 0;
    padding-bottom: 0;
    margin: 0;
  }
  .ant-modal-content {
    display: flex;
    flex-direction: column;
    height: calc(100vh);
  }
  .ant-modal-body {
    flex: 1;
  }
}
.active{
  color:#FF5F5E;
}
</style>
